package com.verlet.springbootdemo.simple.nettyrpc.server;

import com.verlet.springbootdemo.simple.nettyrpc.NettyRpcConstant;
import com.verlet.springbootdemo.simple.nettyrpc.server.codec.RpcInfoDecoder;
import com.verlet.springbootdemo.simple.nettyrpc.server.codec.RpcResultEncoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.json.JsonObjectDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.nio.charset.StandardCharsets;

/**
 * 服务端启动类
 *
 * @author verlet
 * @date 2020/4/19
 */
public class NettyRpcServer {

    public static void main(String[] args) {
        // 用于接收client端连接
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        // 用于实际任务的处理
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        ServerBootstrap bootstrap = new ServerBootstrap();
        try {
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    // tcp 缓冲区
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline()
                                    // 解码器
                                    .addLast(new JsonObjectDecoder())
                                    .addLast(new StringDecoder())
                                    .addLast(new RpcInfoDecoder())
                                    // 编码器
                                    .addLast(new StringEncoder(StandardCharsets.UTF_8))
                                    .addLast(new RpcResultEncoder())

                                    .addLast(new NettyRpcServerHandler());
                        }
                    });
            // bind初始化端口是异步的，但调用sync则会同步阻塞等待端口绑定成功
            ChannelFuture future = bootstrap.bind(NettyRpcConstant.NETTY_RPC_PORT).sync();
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }
}
